﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Runtime.InteropServices;
using System.Diagnostics;


namespace ServerApp
{
    public partial class Form1 : Form
    {
        string Data = "";
        static UDPServices udpServices = new UDPServices();
        static NetworkStream clientStream;
        public String abc;
        Thread th;
        public Form1()
        {
            InitializeComponent();
        }
        // sự kiện double click và rightclick , leftclick
        [DllImport("user32")]
        public static extern int SetCursorPos(int x, int y);
        private const int MOUSEEVENTF_MOVE = 0x0001; /* mouse move */
        private const int MOUSEEVENTF_LEFTDOWN = 0x0002; /* left button down */
        private const int MOUSEEVENTF_LEFTUP = 0x0004; /* left button up */
        private const int MOUSEEVENTF_RIGHTDOWN = 0x0008; /* right button down */
        private const int MOUSEEVENTF_RIGHTUP = 0x0010;
        [DllImport("user32.dll",
            CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons,
            int dwExtraInfo);
        bool kt;
        int x, y;
        IPEndPoint ipendp;
        Socket newsock;
        EndPoint tmpRemote;
        TCPservices tcpSv;

        Image imgOriginal;
        TrackBar zoomSlider = new TrackBar();
        public Image PictureBoxZoom(Image img, Size size)
        {
            Bitmap bm = new Bitmap(img, Convert.ToInt32(img.Width * size.Width), Convert.ToInt32(img.Height * size.Height));
            Graphics grap = Graphics.FromImage(bm);
            grap.InterpolationMode = InterpolationMode.HighQualityBicubic;
            return bm;
        }
        private void zoomSlider_Scroll(object sender, EventArgs e)
        {
            if (zoomSlider.Value > 0)
            {
                picBox.Image = null;
                picBox.Image = PictureBoxZoom(imgOriginal, new Size(zoomSlider.Value, zoomSlider.Value));
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            //zoomSlider.Scroll += new System.EventHandler(zoomSlider_Scroll); 
            //imgOriginal = Image.FromFile(@"C:\New Folder\a.PNG");
            //picBox.Image = imgOriginal;

            //// set Picture Box Attributes
            //picBox.BackgroundImageLayout = ImageLayout.Stretch;

            //// set Slider Attributes
            //zoomSlider.Minimum = 1;
            //zoomSlider.Maximum = 5;
            //zoomSlider.SmallChange = 1;
            //zoomSlider.LargeChange = 1;
            //zoomSlider.UseWaitCursor = false;

            //// reduce flickering
            //this.DoubleBuffered = true;
           

            //ConTrolMouse ct = new ConTrolMouse();
            //th = new Thread(ct.controlmouse);
            //th.Start();

            //IntPtr desktop = GetDC(IntPtr.Zero);
            //using (Graphics g = Graphics.FromHdc(desktop))
            //{
            //    g.FillRectangle(Brushes.Red, 0, 0, 100, 100);
            //}
            //ReleaseDC(desktop);

            try
            {
                udpServices.server_Load();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }         
        }

        public void demo()
        {
            int port = 8080;
            byte[] data = new byte[1400];
            ipendp = new IPEndPoint(IPAddress.Any, port);
            newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            newsock.Bind(ipendp);
            tmpRemote = (EndPoint)(ipendp);
            tcpSv = new TCPservices();
            kt = false;

            while (!kt)
            {
                bool click = false;
                bool rightClick = false;
                data = new byte[1400];

                int recv = newsock.ReceiveFrom(data, ref tmpRemote);
                if (recv > 0)
                {
                    string s = Encoding.ASCII.GetString(data);
                    string[] temp = s.Split('\0');
                    s = temp[0];

                    temp = s.Split(';');
                    if (temp.Count() >= 2)
                    {
                        x = (int)float.Parse(temp[0]);
                        x = x * 5 / 2;
                        y = (int)float.Parse(temp[1]);
                        y = y * 5 / 2;
                    }
                    else
                    {
                        x = 0;
                        y = 0;
                    }


                    if (temp.Count() > 2 || temp.Count() == 1)
                    {
                        click = true;
                        if (temp.Count() == 1)
                        {
                            rightClick = true;
                        }
                    }

                    if (ketqua.InvokeRequired)
                    {
                        Cursor.Position = new Point(x + Cursor.Position.X, y + Cursor.Position.Y);

                        if (click)
                        {
                            SetCursorPos(x + Cursor.Position.X, y + Cursor.Position.Y);

                            if (rightClick)
                            {
                                mouse_event(MOUSEEVENTF_RIGHTDOWN, Cursor.Position.X, Cursor.Position.Y, 0, 0);
                                mouse_event(MOUSEEVENTF_RIGHTUP, Cursor.Position.X, Cursor.Position.Y, 0, 0);
                            }
                            else
                            {
                                mouse_event(MOUSEEVENTF_LEFTDOWN, x + Cursor.Position.X, y + Cursor.Position.Y, 0, 0);
                                mouse_event(MOUSEEVENTF_LEFTUP, x + Cursor.Position.X, y + Cursor.Position.Y, 0, 0);
                            }
                        }

                    }
                    else
                    {
                        //di chuyển nó đến xy
                        Cursor.Position = new Point(x + Cursor.Position.X, y + Cursor.Position.Y);
                        //Cursor.Position = new Point(x, y);
                        //trích cho nó 1 nhát
                        //mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, Cursor.Position.X, Cursor.Position.Y, 0, 0);


                        //ketqua.Text = s;

                        if (click)
                        {
                            SetCursorPos(x + Cursor.Position.X, y + Cursor.Position.Y);

                            if (rightClick)
                            {
                                mouse_event(MOUSEEVENTF_RIGHTDOWN, Cursor.Position.X, Cursor.Position.Y, 0, 0);
                                mouse_event(MOUSEEVENTF_RIGHTUP, Cursor.Position.X, Cursor.Position.Y, 0, 0);
                            }
                            else
                            {
                                mouse_event(MOUSEEVENTF_LEFTDOWN, x + Cursor.Position.X, y + Cursor.Position.Y, 0, 0);
                                mouse_event(MOUSEEVENTF_LEFTUP, x + Cursor.Position.X, y + Cursor.Position.Y, 0, 0);
                            }
                        }
                    }
                }
            }

        }

        //public void settext(string s, int x, int y)
        //{
        //    //di chuyển nó đến xy
        //    Cursor.Position = new Point(x, y);
        //    //trích cho nó 1 nhát
        //    //mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, Cursor.Position.X, Cursor.Position.Y, 0, 0);

        //    ketqua.Text = s;
        //}

        public void returnIP()
        {
            String abc = udpServices.returnIP();
            MessageBox.Show("IP is : " + abc);
        }


        public void run()
        {
            TcpClient client = new TcpClient();
            IPEndPoint serverEndpoint = new IPEndPoint(IPAddress.Parse("192.168.1.146"), 8080);
            client.Connect(serverEndpoint);
            clientStream = client.GetStream();
            ASCIIEncoding encoder = new ASCIIEncoding();
            byte[] buffer;
            while (true)
            {
                buffer = encoder.GetBytes("GO");
                clientStream.Write(buffer, 0, buffer.Length);
                clientStream.Flush();
            }
        }
        public void duyetfile()
        {
            FolderBrowserDialog b = new FolderBrowserDialog();
            b.ShowDialog();


            string path = b.SelectedPath;
            DirectoryInfo dInfo = new DirectoryInfo(path);
            FileInfo[] files = dInfo.GetFiles();

            for (int i = 0; i < files.Length; i++)
            {
                string filename = files[i].Name;
                int length = filename.LastIndexOf(".");// lấy chiều dài của file
                // từ đầu đến dấu chấm
                String DuoiFile = filename.Substring(length + 1);
                if (DuoiFile.Equals("ppt") || DuoiFile.Equals("pptx"))
                {
                    string path_filename = path + filename;
                    Data += path_filename;
                    Data += ";";
                }
            }
        }


        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (th != null)
            {
                th.Abort();
            }
            Application.ExitThread();
            Application.Exit();
            
        }

    }
}
